import tinymce from "tinymce";

tinymce.PluginManager.add("wordlimit", function (editor) {
	let pluginName = "字数限制";
	let global$1 = tinymce.util.Tools.resolve("tinymce.util.Tools");
	let global$2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
	let wordlimit_type = editor.getParam("wordlimit_type", "letter");
	let wordlimit_num = editor.getParam("wordlimit_num", false);
	let wordlimit_delay = editor.getParam("wordlimit_delay", 500);
	let wordlimit_callback = editor.getParam("wordlimit_callback", function () {
	});
	let wordlimit_event = editor.getParam("wordlimit_event", "SetContent Undo Redo Keyup");
	let onsign = 1;
	//统计方法1：计算总字符数
	let sumLetter = function () {
		let html = editor.getContent();
		let re1 = new RegExp("<.+?>", "g");
		let txt = html.replace(re1, "");
		txt = txt.replace(/\n/g, "");
		txt = txt.replace(/&nbsp;/g, " ");
		let num = txt.length;
		return {txt: txt, num: num};
	};
	let onAct = function (res) {
		if (onsign) {
			onsign = 0;
			//此处预留更多统计方法
			switch (wordlimit_type) {
				case "letter":
				default:
					let res = sumLetter();
			}
			if (res.num > wordlimit_num) {
				wordlimit_callback(editor, res.txt, wordlimit_num);
			}
			setTimeout(function () {
				onsign = 1;
			}, wordlimit_delay);
		}
		
	};
	let setup = function () {
		if (wordlimit_num > 0) {
			global$2.setEditorTimeout(editor, function () {
				let doth = editor.on(wordlimit_event, onAct);
			}, 300);
		}
	};
	
	setup();
	
	return {
		getMetadata: function () {
			return {
				name: pluginName,
				url: "http://tinymce.ax-z.cn/more-plugins/wordlimit.php"
			};
		}
	};
});
